package org.example;

import lombok.SneakyThrows;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

public class MysqlConn {

    private Connection connection;
    private PreparedStatement preparedStatement;

    /*
    * 初始化
    * */
    MysqlConn()  {

        String driver = "com.mysql.cj.jdbc.Driver";
        //本地连接ip
//        String url = "jdbc:mysql://127.0.0.1:3306/temp?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8";
//        String user="root";
//        String password="123456";
//        //远程ip
        String url = "jdbc:mysql://101.42.19.16:3306/temp?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8&autoReconnect=true";
        String user = "temp";
        String password = "123456";
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /*
    * todo 添加数据
    * */

    @SneakyThrows
    public void add(Long time, String data,int partition) {

        //建立语句
//        String sql ="insert into datafromkafka(time,temp1,temp2,temp3,temp4,temp5,humdy) values (?,?,?,?,?,?,?)";
        //特定partition对应特定的表
        String table = "device"+String.valueOf(partition+1);
        String sql ="insert into "+table+"(time,temp1,temp2,temp3,temp4,temp5,humdy) values (?,?,?,?,?,?,?)";
        preparedStatement =connection.prepareStatement(sql);
        //数据抽取
        String str_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);//毫米级时间戳转换为时间格式
        String[] split_data = data.split(" ");


        /*
        * 执行语句
        * */
        preparedStatement.setString(1,str_time);
        int i=2;
        while (i<=7){
            preparedStatement.setString(i,split_data[i-2]);
            i++;
        }
        preparedStatement.executeUpdate();//执行语句
        System.out.println("Mysql添加数据成功"+partition);
    }


}
